var crypto = require('../utils/crypto');
var express = require('express');
var db = require('../db');
//var http = require("../utils/http");

var app = express();
//var hallAddr = "";

function send(res,ret){
    var str = JSON.stringify(ret);
    res.send(str)
}

var config = null;

//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

exports.start = function(cfg){
    config = cfg;
    //hallAddr = config.IP  + ":" + config.HALL_CLIENT_PORT;
    app.listen(config.PORT);
    console.log("account server is listening on " + config.PORT);
}

app.get('/login', function(req, res){
    var account = req.query.account;
    var password = req.query.password;

    var fnFailed = function(msg){
        send(res,{errcode:1, errmsg: msg});
    };

    var fnSucceed = function(){
        send(res,{errcode:0, errmsg:"ok"});  
        console.log("[ fnSucceed errorcode: 0, errmsg: ok");
    };

    //检测账号存不存在
    db.is_esxit_account(account, function(ret) {
        if (ret) {
            //检测密码对不对
            db.is_account_password(account, password, function(ret) {
                if (ret) {
                    fnSucceed();
                } else {
                    fnFailed("密码错误!");
                }
            })
        } else {
            //注册添加新账号
            db.create_account(account, password, function(ret) {
                if (ret) {
                    //创建新用户成功
                    fnSucceed();
                } else {
                    fnFailed('注册失败,请重试其他账号！');
                    console.log("[调试：新增用户密码失败!!!");
                }
            })
        }
    })
});